package com.j3.string;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {

	public static String getDomainString(String emailAddress) {
		int indexAt = emailAddress.indexOf('@');
		if (indexAt < 0) {
			return null;
		}
		return emailAddress.substring(indexAt + 1).toLowerCase();
	}


	public static String isoToGBK(String sourceString) throws UnsupportedEncodingException {
		if (sourceString == null) {
			return null;
		}
		return new String(sourceString.getBytes("iso8859-1"), "GBK");
	}

	public static List<String> searchRegExpString(String txt, String regex, boolean allowDuplicated) {
		return searchRegExpString(txt, regex, allowDuplicated, 0);
	}


	public static List<String> searchRegExpString(String text, String regex, boolean allowDuplicated, int groupId) {
		ArrayList<String> list = new ArrayList<String>();
		Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(text);
		String string = null;
		while (matcher.find()) {
			string = matcher.group(groupId);
			if (!allowDuplicated && list.contains(string)) {
				continue;
			}
			list.add(string);
		}
		return list;
	}

	public static String getFirstMatchedText(String content, String regex) {
		return getFirstMatchedText(content, regex, 0);
	}

	public static String getFirstMatchedText(String content, String regex, int groupId) {
		Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(content);
		if(matcher.find()) {
			return matcher.group(groupId);
		}
		return null;
	}

	public static String multiReplace(String txt, Map<String, String> replaceMap) {
		if (replaceMap == null || replaceMap.size() == 0 || txt == null || txt.length() == 0) {
			return txt;
		}

		for(Map.Entry<String, String> entry : replaceMap.entrySet()) {
			String regex = entry.getKey();
			String replacement = entry.getValue();
			if (replacement == null) {
				continue;
			}
			replacement = replacement.replace("$", "\\$");
			txt = txt.replaceAll(regex, replacement);
		}
		return txt;
	}

	public static String multiReplaceLiteral(String txt, Map<String, String> replaceMap) {
		if (replaceMap == null || replaceMap.size() == 0 || txt == null || txt.length() == 0) {
			return txt;
		}
		for(Map.Entry<String, String> entry : replaceMap.entrySet()) {
			String key = entry.getKey();
			String replacement = entry.getValue();
			if (replacement == null) {
				replacement = "";
			}
			txt = txt.replace(key, replacement);
		}
		return txt;
	}

	public static String replicate(String string, int times) {
		if (times <= 0) {
			return "";
		}
		StringBuilder buffer = new StringBuilder();
		for (int i = 0; i < times; i++) {
			buffer.append(string);
		}
		return buffer.toString();
	}

	public static String lpad(String source, char c, int destLength) {
		int srcLength = source.length();
		int balance = destLength - srcLength;
		if (balance <= 0)
			return source;
		char[] buf = new char[destLength];
		for (int i = 0; i < balance; i++) {
			buf[i] = c;
		}
		source.getChars(0, srcLength, buf, balance);
		return new String(buf);
	}

	public static String lpad(Object obj, char chr, int len) {
		if (obj == null) {
			return lpad("", chr, len);
		}
		return lpad(obj.toString(), chr, len);
	}

	public static String rpad(String source, char c, int destLength) {
		int srcLength = source.length();
		int balance = destLength - srcLength;
		if (balance <= 0)
			return source;
		char[] buf = new char[destLength];
		for (int i = 0; i < balance; i++) {
			buf[i + srcLength] = c;
		}
		source.getChars(0, srcLength, buf, 0);
		return new String(buf);
	}

	public static String rpad(Object obj, char chr, int len) {
		if (obj == null) {
			return rpad("", chr, len);
		}
		return rpad(obj.toString(), chr, len);
	}

	public static String left(String string, int len) {
		if (string.length() <= len) {
			return string;
		}
		return string.substring(0, len);
	}

	public static String right(String string, int len) {
		int size = string.length();
		if (size <= len) {
			return string;
		}
		return string.substring(size - len);
	}

	public static String ltrim(String string, char chr) {
		if (string == null || string.length() == 0) {
			return string;
		}
		int len = string.length();
		int pointer = 0;
		while (pointer < len && string.charAt(pointer) == chr) {
			pointer++;
		}
		if (pointer >= string.length()) {
			return "";
		}
		return string.substring(pointer, string.length());
	}

	public static String rtrim(String string, char chr) {
		if (string == null || string.length() == 0) {
			return string;
		}
		int pointer = string.length() - 1;
		while (pointer >= 0 && (string.charAt(pointer) == chr)) {
			pointer--;
		}
		if (pointer < 0) {
			return "";
		}
		return string.substring(0, pointer + 1);
	}

	public static String trim(String string, char chr) {
		return rtrim(ltrim(string, chr), chr);
	}

	public static String toHTML(String string) {
		HashMap<String, String> replaceMap = new HashMap<String, String>();
		replaceMap.put("<", "\\&lt\\;");
		replaceMap.put(">", "\\&gt\\;");
		replaceMap.put("\"", "&quot;");
		replaceMap.put("\r\n", "<br>");
		replaceMap.put("\n", "<br>");
		replaceMap.put(" ", "\\&nbsp\\;");
		return multiReplace(string, replaceMap);
	}

	public static String safeReplace(String string) {
		HashMap<String, String> replaceMap = new HashMap<String, String>();
		replaceMap.put("<", "\\&lt\\;");
		replaceMap.put(">", "\\&gt\\;");
		replaceMap.put("\"", "&quot;");
		// replaceMap.put("&", "&amp;");
		return multiReplace(string, replaceMap);
	}

	public static String toOptions(String string, String regex, String defaultValue) {
		StringBuilder buffer = new StringBuilder(512);
		String[] matrix = string.split(regex);
		for (int i = 0; i < matrix.length; i++) {
			buffer.append("<option value=\"");
			buffer.append(matrix[i]).append("\"");
			if (matrix[i] != null && matrix[i].equals(defaultValue)) {
				buffer.append(" selected>");
			}
			buffer.append(matrix[i]).append("</option>");
		}
		return buffer.toString();
	}

	public static String capitalize(String string) {
		if (string == null) {
			return null;
		}
		int len = string.length();
		if (len == 0) {
			return "";
		}
		if (len == 1) {
			return string.toUpperCase();
		}
		String a = string.substring(0, 1);
		String b = string.substring(1);
		return a.toUpperCase() + b;
	}

	public static String underlineToCapitalize(String string) {
		StringBuilder buffer = new StringBuilder();
		int len = string.length();
		char temp = ' ';
		for (int i = 0; i < len; i++) {
			char chr = string.charAt(i);
			if (chr == '_') {
				temp = chr;
				continue;
			}
			if (temp == '_') {
				buffer.append(Character.toUpperCase(chr));
			} else {
				buffer.append(chr);
			}
			temp = chr;
		}
		return buffer.toString();
	}

	public static String capitalizeToUnderline(String string) {
		StringBuilder buffer = new StringBuilder();
		int len = string.length();
		for (int i = 0; i < len; i++) {
			char chr = string.charAt(i);
			if (i > 0 && Character.isUpperCase(chr)) {
				buffer.append('_');
				buffer.append(Character.toLowerCase(chr));
				continue;
			}
			buffer.append(chr);
		}
		return buffer.toString();
	}

	public static int compare(String s1, String s2) {
		if (s1 == null) {
			if (s2 == null) {
				return 0;
			}
			return -1;
		}
		if (s2 == null) {
			return 1;
		}
		if (s1.equals(s2)) {
			return 0;
		}
		int len1 = s1.length();
		int len2 = s2.length();
		for (int i = 0; i < len1 && i < len2; i++) {
			int c1 = s1.charAt(i);
			int c2 = s2.charAt(i);
			if (c1 > c2) {
				return 1;
			} else if (c1 < c2) {
				return -1;
			}
		}
		if (len1 > len2) {
			return 1;
		}

		return -1;
	}

	public static String getBrief(String sourceString, int len) {
		int l = sourceString.length();
		boolean flag = false;
		for (int i = 0; i < sourceString.length(); i++) {
			if (sourceString.substring(i, i + 1).matches("[\\u4e00-\\u9fa5]+")) {
				flag = true;
				break;
			}
		}
		if (flag) {
			if (l > (len / 2 + 1)) {
				return sourceString.substring(0, len / 2) + "...";
			}
		} else {
			if (l > (len + 1)) {
				return sourceString.substring(0, len) + "...";
			}
		}
		return sourceString;
	}

	public static String getRandomCode(int len) {
		StringBuilder buffer = new StringBuilder();
		buffer.append(System.currentTimeMillis());
		Random r = new Random();
		while (buffer.length() < len) {
			buffer.append(r.nextInt(10));
		}
		return buffer.toString();
	}

	public String toString() {
		return "version 1.0, date 2004.06.10 author river";
	}

	public static boolean isNotBlank(String text) {
		return text != null && text.trim().length() > 0;
	}

	public static boolean isBlank(String text) {
		return !isNotBlank(text);
	}

	public static String[] splitAndTrim(String text, String regex) {
		String[] elements = text.split(regex);
		for (int i = 0; i < elements.length; i++) {
			elements[i] = elements[i].trim();
		}
		return elements;
	}
	
	public static String formatCsvStr(String str){
	  if(isNotBlank(str)){
	  	str = str.replaceAll("\"", "\"\"");
	  	str = str.replaceAll(",", "\",\"");
	  	str = "\"" + str + "\"";
	  }
    return str;
	}
}
